package com.learning.servlet2x.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: ServletContextServlet
 * Description: 上下文配置
 * Date: 2018/6/24 7:40 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ServletContextServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 ServletConfig 配置，只对某个 Servlet 有效
        String servlet_user = super.getInitParameter("servlet_user");
        System.out.println("本 Servlet 私有的配置： " + servlet_user);


        // 获取 ServletContext 配置，最对所有 Servlet 有效
        ServletContext servletContext = super.getServletContext();
        String context_user = servletContext.getInitParameter("context_user");
        System.out.println("所有的 Servlet 共有的配置： " + context_user);


        //
        servletContext.setAttribute("newUser", "Eason");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 所有servlet实现通信,使用 上下文 Context 域
        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("new_user", "Eason");
        String new_user = (String) servletContext.getAttribute("new_user");
        System.out.println("所有servlet实现通信: " + new_user);
        servletContext.removeAttribute("new_user");
        servletContext.getAttributeNames();
    }
}
